import requests
import json
from typing import List, Dict
from requests.exceptions import RequestException


class AllianceConstant:
    UrlConstant = {
        "CARD_ADD_URL": "https://open.douyinec.com/alliance/card/add"
    }
    ALLIANCE_COMMON_ERROR_MESSAGE = "联盟系统错误，请联系三只羊官方人员"


def cardBatchTmp(userId: str, displayId: str, openId: str, accessToken: str, products: List[Dict]) -> List[Dict]:
    if not products:
        return None

    card_add_url = f"{AllianceConstant.UrlConstant['CARD_ADD_URL']}?open_id={openId}"
    card_param = {
        "products": products,
        "pick_extra": str(userId),
        "keep_picksource": True
    }
    print(f" 开始添加选品车 抖音号: {displayId}")

    try:
        response = requests.post(
            card_add_url,
            headers={
                "Access-Token": accessToken,
                "Content-Type": "application/json"
            },
            json=card_param
        )
        response.raise_for_status()  # 检查请求是否成功
        card_body = response.json()
        # print(json.dumps(card_body, ensure_ascii=False, indent=2))
        print(card_body)

        if not card_body:
            raise ValueError("选品车添加系统错误，请联系三只羊官方人员")

        err_no = card_body.get("err_no")
        if err_no is not None and err_no != "0":
            if err_no == "28001008":
                raise ValueError(f"{AllianceConstant.ALLIANCE_COMMON_ERROR_MESSAGE} {displayId}")
            else:
                raise ValueError(card_body.get("err_msg"))

        data = card_body.get("data")
        if not data:
            raise ValueError("选品车添加系统错误，响应data为空，请联系三只羊官方人员")

        results = data.get("results")
        if not results:
            raise ValueError("选品车添加系统错误，响应results为空，请联系三只羊官方人员")

        return results

    except RequestException as e:
        print(f"请求失败: {e}")
        return None
    except ValueError as e:
        print(f"处理响应失败: {e}")
        return None


# 示例数据
userId = "12096"
displayId = "zdw5147"
openId = "_000Y3IuK-AJPX4lJumkSZP0uEpf5IZWLK-6"
accessToken = "act.6104ae8e33eef6407fa1c31c74925b08IgHu8z2eozFNywMi9lc0JBLRgmPo_hl"
products = [
    {
        "activity_url": "https://haohuo.jinritemai.com/ecommerce/trade/detail/index.html?ins_activity_param=i6DEpTRv&id=3468957082743651847&origin_type=pc_buyin_group",
        "product_id": "3468957082743651847"},
]

# 调用函数
# results = cardBatchTmp(userId, displayId, openId, accessToken, products)
# if results:
#     print("选品车添加成功，结果如下：")
#     print(json.dumps(results, ensure_ascii=False, indent=2))
# else:
#     print("选品车添加失败")
